package com.example.websocket.another.config;

import com.example.websocket.another.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;


@Configuration
@EnableWebSocketMessageBroker
@Slf4j
@Component
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

//    /**
//     * STOMP监听类 不用了 用 WebSocketEventListener
//     *
//     * @return
//     */
//    @Bean
//    public StompConnectEventListener applicationStartListener() {
//        return new StompConnectEventListener();
//    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        //建立连接端点，注册一个STOMP的协议节点,并指定使用SockJS协议
        stompEndpointRegistry.addEndpoint("/nmpSocketWeb")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
        //配置消息代理（MessageBroker）。
        // 推送消息前缀
        messageBrokerRegistry.enableSimpleBroker("/topic");
        // 应用请求前缀，前端发过来的消息将会带有“/app”前缀。
        messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
    }

    /**
     * token拦截认真
     *
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        //token认证
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                assert accessor != null;
                if (StompCommand.CONNECT.equals(accessor.getCommand()) || StompCommand.SEND.equals(accessor.getCommand())) {
                    String token = accessor.getFirstNativeHeader(JwtUtil.header);
                    try {
                        JwtUtil.validateToken(token);
                    } catch (Exception e) {
                        log.error("验证token异常！{}", e.toString());
                        return null;
                    }
                }
                return message;
            }
        });
    }


}